#!/usr/bin/ruby
require "rubygems"
require "nokogiri"
require "open-uri"
require File.expand_path("../../album", __FILE__)

class DoubanAlbum < Album
  def initialize
    super
    @regex = /http:\/\/www.douban.com\/photos\/album\/\d+\//
    @verified_urls = []
  end
  
  def go
    time_start = Time.now
    begin      
      verify_urls
      @verified_urls.each do |url|
        @current_url = url
        get_url_for_pics
        create_ablum_folder
        get_remote_pics
      end
    rescue NoValidUrlError => e
      puts e.message, e.backtrace
    end
    puts "Costing time: #{Time.now - time_start}"
  end
  
  protected 
    
    def verify_urls
      @urls.each do |url|
        if @regex =~ url
          @verified_urls << url
        end
      end
      raise NoValidUrlError, "No url is valid! Please input corrent ones!" if @verified_urls.empty?
    end
    
    def get_url_for_pics
      puts "You are downloading douban pics from #{@current_url}"
      @doc = Nokogiri::HTML(open(@current_url))
      @folder_name = /\d+/.match(@current_url).to_s + "_" + @doc.css('h1').inner_text
      @sum = @doc.css('.wr span.pl').inner_text.to_i
      raise NoValidPicError, "This is an invalid ablum!" if @sum.nil?
      
      i, times, @image_urls = 0, @sum/18, []
      while i <= times do
        page = Nokogiri::HTML(open(@current_url+"?start="+(i*18).to_s))
        page.css(".photo_wrap a img").each do |img|
          @image_urls << img.attribute("src").to_s.sub(/thumb/, "photo")
        end 
        i += 1
      end
    end
    
    def get_remote_pics(use_threads=false)
      if use_threads
        puts "Downloading starts in multi-threads way."
        threads = []
      else
        puts "Downloading starts in normal way."
      end
      @image_urls.each_with_index do |img, i|
        regex = /p\d+\.jpg/
        dest = regex.match(img).to_s
        output_file = File.join(@folder_name, dest)
        if use_threads 
          threads << Thread.new do 
            stream = open(img) { |f| f.read }
            open(output_file, "wb") do |f|
              puts "creating file #{output_file} from #{@image_urls[i]} ... #{i+1}/#{@image_urls.count}"
              f.write(stream)
            end
          end
        else
          stream = open(img) { |f| f.read }
          open(output_file, "wb") do |f|
            puts "creating file #{output_file} from #{@image_urls[i]} ... #{i+1}/#{@image_urls.count}"
            f.write(stream)
          end
        end
      end
      if use_threads
        threads.each { |t| t.join }
      end
      puts "Downloading douban pics from #{@current_url} has completed!"
    end
end

DoubanAlbum.new.go
